/*
 * @Author: codeD
 * @Date: 2022-02-17 23:42:36
 * @LastEditors: codeD
 * @LastEditTime: 2022-02-19 10:06:31
 * @Description: file content
 * @FilePath: \wpt\src\pages\Classification\effect.tsx
 */
import { useEffect, useState, RefObject, createRef, useRef, } from 'react';
import {useNavigate  } from 'react-router-dom';
import { GoodsList,Ids } from './type'

export const useClassIfy = () => {
    const [goodsList, setGoodsList] = useState<GoodsList>([] as GoodsList)
    const [currentShow,setCurrentShow]=useState<number>(0)
    const [doms,setDoms] = useState<RefObject<HTMLDivElement>[]>([])
    const [lastIndex,setIndex]=useState(-1)
    // let lastIndex=-1
    const getList = async () => {
        const { data: data } = await fetch('https://api.weipaitang.com/wechat/v1.0/category/get-list?__uuri=&_h=XH5%3DkDM6p1TCR1UVFDMkZkUsR1drZkVOh2VSRFbFFmROZ1UhYx&_a=139_868_1645101245').then(res => res.json()).then(res => res)
        return data  
    }
    const handleChangeTab = (index: number) => {
      
        const dom = document.querySelector(`#tab-item-${index}`);
        setCurrentShow(index)
        dom?.scrollIntoView({
          behavior: "smooth"
        });
    
        setTimeout(()=>{
            setIndex(index) 
        }, 700)
      }
      const navigators=( cateId:number,secCateId:number)=>{
          window.history.pushState(null , '', `/classdetail/complete/${cateId}/${secCateId}`);
         window.location.reload()
      }
  const observes = (dom: Element, index: number) => {
    if(lastIndex===-1){
        return
    }
    const intersectionObserver = new IntersectionObserver(function (entries) {     
      if (entries[0].intersectionRatio > 0) {
     
          setCurrentShow(index)         
      }        
    });
    intersectionObserver.observe(dom);
  }
  useEffect( () => {
   getList().then(res=>{
    const newArr = res.categoryList.map(() => createRef()) 
    setDoms([...newArr])
    setGoodsList(res.categoryList) 
   })
   
  }, [])
  useEffect(()=>{
    setIndex(currentShow)
  },[currentShow])
  
  useEffect(()=>{
    setTimeout(()=>{        
        setIndex(0)
        }, 500)
      setTimeout(()=>{
        doms.forEach((item, index) => {
            const { current } = item;
            if (current) {
              observes(current, index);
            }
          })
      },500)
      
  },[doms])
   
    return {
        goodsList,
        doms,
        currentShow,
        handleChangeTab,
        navigators
    }
}
